
<template>
    <div>
        <div class="clearfix margin-top-20">
            <Row >
                <Col span="6">
                    <div class="back-fff margin-right-15 border-primary">
                        <div class="litTitle">销售额 <Tooltip>
                            <Icon type="md-help-circle" />
                            <template #content>
                                <p>不包含cancel和pending订单，</p>
                                <p>金额不包含Tax和shipping price</p>
                            </template>
                        </Tooltip></div>
                        <div class="padding-10 height-90">
                            <div class="font-32 font-weight">${{allmount.toFixed(2) || 0}}</div>
                        </div>
                    </div>
                </Col>
                <Col span="6">
                    <div class="back-fff margin-right-15 border-error">
                        <div class="litTitle">订单总数量 <Tooltip content="不包含cancel和pending订单"><Icon type="md-help-circle" /></Tooltip></div>
                        <div class="padding-10 height-90">
                            <div class="font-32 font-weight">{{alltotal || 0}}</div>
                        </div>
                    </div>
                </Col>
                <Col span="6">
                    <div class="back-fff margin-right-15 border-warning">
                        <div class="litTitle">总退货量</div>
                        <div class="padding-10 height-90">
                            <div class="font-32 font-weight">{{titlebox3.product_count || 0}}</div>
                            <div class="font-14">${{titlebox3.subtotal.toFixed(2)}}</div>
                        </div>
                    </div>
                </Col>
                <Col span="6">
                    <div class="back-fff border-success">
                        <div class="litTitle">未发货订单 <Tooltip content="pending订单"><Icon type="md-help-circle" /></Tooltip></div>
                        <div class="padding-10 height-90">
                            <div class="font-32 font-weight">{{titlebox4.unship_orders_count || 0}}</div>
                            <div class="font-14">${{titlebox4.pending_amount.toFixed(2)}}</div>
                        </div>
                    </div>
                </Col>
            </Row>
        </div>
        <div class="clearfix margin-top-20 ">
            <Row>
            <Col span="24" class="home-card-head back-fff">
                <div class="ivu-row-flex ivu-row-flex-middle ivu-row-flex-center font-14">
                    <Col span="8" class="">销售曲线图</Col>
                    <Col span="16" class="text-right" >
                        <div class="ivu-radio-group">
                            <label class="ivu-radio-wrapper ivu-radio-group-item ivu-radio-default" :class="{'ivu-radio-wrapper-checked':defaultdate==index}" v-for="(item,index) in dateList" :key="index" @click="changedate(item,index)">{{item.label}}</label>
                        </div>
                        <div class="ivu-date-picker" style="width:200px;">
                            <DatePicker type="daterange"
                                    class="margin-right-10"
                                    placement="bottom-end"
                                    placeholder="选择时间"
                                    style="width:220px;"
                                    :value="getshipdate"
                                    @on-change="handleChange"
                            ></DatePicker>
                        </div>
                        <span style="width:75px;display:inline-block">项目</span>
                        <div class="ivu-date-picker margin-left-10" style="width:200px;">
                            <Select v-model="lineId" filterable clearable multiple class="text-left" label="123">
                                <Option v-for="(item,index) in getNewDifferentAllProductList" :key="index" :value="item.value">{{item.label}}</Option>
                            </Select>
                        </div>
                        <Button class="margin-left-10" type="primary" @click="getpeding">查询</Button>
                    </Col>
                </div>
            </Col>
            </Row>
            <Row>
            <Col span="24" class="back-fff">
                <Col span="24" class="padding-right-20" style="position:relative">
                    <!-- 折线图 -->
                    <div class="back-fff">
                        <div class="text-right padding-top-10 padding-right-10">
                            <Button v-if="showliang" class="margin-right-10" @click="clickliang"><Icon type="ios-git-compare" />切换销售量</Button>
                            <Button v-if="!showliang" class="margin-right-10" @click="clickliang"><Icon type="ios-git-compare" />切换销售额</Button>
                        </div>
                        <div id="LineGraph" style="height: 350px;width:100%"></div>
                    </div>
                    <div class="margin-top-10 text-center">以上数据是销售订单的实时统计数据（以订单创建时间为准）；数据会实时变化，仅供参考</div>
                    <Sign class="homeloading" fix :show="loading1"></Sign>
                </Col>
                
            </Col>
            </Row>
            <Row class="margin-top-20">
                <Col span="16" class="padding-right-20" style="position:relative">
                    <div class="back-fff">
                    <div>
                        <Button v-if="showpie" class="pull-right margin-right-10 margin-top-10" @click="clickpie(1)"><Icon type="ios-git-compare" />切换库存分布</Button>
                        <Button v-if="!showpie" class="pull-right margin-right-10 margin-top-10" @click="clickpie(2)"><Icon type="ios-git-compare" />切换按体积统计</Button>
                    </div>
                    <div style="overflow:hidden">
                        <!-- 饼图 -->
                        <div id="pieGraph" style="height: 350px;width:100%;padding:20px"></div>
                    </div>
                    <Sign class="homeloading" fix :show="loading2"></Sign>
                </div>
                </Col>
                <Col span="8">
                    <!-- 第一板块 -->
                    <div class="back-fff" style="min-height:350px">
                        <div class="gonggao">
                            <Icon type="md-volume-up" /><span style="color:#515a6e">公告</span>
                            <span class="pull-right margin-right-10"><a @click="clickNewslist">更多 >></a></span>
                        </div>
                        <!-- 公告板块 做滚动加页面站位-->
                        <div class="scrollbox">
                            <ul class="scrollUl" >
                                <li :title="item.title" v-for="(item, index) in noticeList" :key="index">
                                    <Tooltip content="置顶" v-if="item.weight>0"><Icon class="color-error margin-right-5" type="star"></Icon></Tooltip><a @click="clickItemNews(item.id)" class="liitem">{{item.title}}</a></li>
                            </ul>
                        </div>
                    </div>
                </Col>
            </Row>
        </div>
        <!-- 单条内容弹框 -->
        <vModal
        class="hidefooter"
        v-model="operate.show"
        v-bind="operate"
        :showFooter="false"
        >
            <!-- <compContent :itemId="itemid" ></compContent> -->
            <component @on-close="operate.show = false" :id="operate.id" :is="operate.component"></component>
        </vModal>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { 
    HttpGetSalenData,
    HttpGetSales,
    HttpGetPending,
    HttpGetAnnouncement,
    HttpInventoryProportion,
    HttpAccountStat,
    HttpGetReturn,
} from '../../service/homepage'
import {
    HttpRecentAnnounceList
} from '../../service/notice'
import compContent from './homelist/content'
import compDetail from '../../views/notice/announce/detailmodal'
import compSetAccount from './homelist/setupaccount'
import MyStorage from '../../utils/mystorage'
export default {
    data(){
        return {
            lineId:null,
            channelId:"",
            returnAt:"",
            animate:false,
            showliang:false,
            showpie:false,
            noticeList: [],
            beforedaylist:[],
            beforeQuantity:[],
            beforeAmount:[],
            nowdaylist:[],
            nowQuantity:[],
            nowAmount:[],
            allmount:0,
            alltotal:0,
            titlebox3:{
                subtotal:0,
            },
            titlebox4:{
                pending_amount:0,
            },
            pieList:[],
            myaccount:{},
            loading1:false,
            loading2:false,
            homeContent:'',
            operate:{
                show:false,
                title:'',
                footer:true,
                width:1000,
            },
            itemid:'',
            monthday:'',
            oldmonth:'',
            getshipdate:[],
            dateList:[
                {label:"14日",value:1},
                {label:"本月",value:2},
                {label:"上月",value:3},
            ],
            defaultdate:0,
        }
    },
    components:{compContent, compDetail,compSetAccount},
    computed:{
        ...mapGetters('dictionary',['getNewDifferentAllProductList']),
    },
    created () {
        this.update()
    },
    mounted(){
        // 获取时间
        this.newtimes()
    },
    methods:{
        jumpfbb(){
            window.open(process.env.VUE_APP_FBB+'/home/account#', '_blank');
            
        },
        newtimes(){
            var date = new Date();
            var year = date.getFullYear();
            var newmonth = date.getMonth() + 1;
            // var strDate = date.getDate();
            // console.log(newmonth)
            if (newmonth >= 1 && newmonth <= 9) {
                this.monthday = year + "-" + "0" + newmonth;
                if(newmonth == 1){
                    this.oldmonth = year-1 + "-" + 12
                }else{
                    this.oldmonth = year + "-" + "0" + --newmonth
                }
            }else{
                this.monthday = year + "-" + newmonth;
                this.oldmonth = year + "-" + --newmonth
            }
        },
        handleChange(value){
            // console.log(value)
            if(value[0] == '' || value[1] =='') return
            let arrdate1 = new Date(value[0])
            let arrdate2 = new Date(value[1])
            let itemdate = arrdate2.getTime() - arrdate1.getTime()
            let daynum = Math.floor(itemdate / (parseFloat(24 * 60 * 60 * 1000)))
            // console.log(daynum)
            if( daynum > 30 ){
                this.$Message.error('请选择小于30天的日期区间')
            }else{
                let beginDate = value[0]
                let endDate = value[1]
                this.getshipdate = [beginDate,endDate]
                // this.getpeding()
            }
            // console.log(itemdate2,itemdate1)
        },
        // 切换头部日期
        changedate(date,index){
            this.defaultdate = index
            // console.log(date,index)
            if(date.value == 1){
                this.timehandle()
                // this.timehandle()
                this.getpeding()
            }else if(date.value == 2){
                var TimeNow = new Date();
                let beginDate = TimeNow.getFullYear() +'-'+ this.doHandleMonth(TimeNow.getMonth() + 1) +'-'+ '01';//当月1号
                let endDate = TimeNow.getFullYear() +'-'+ this.doHandleMonth(TimeNow.getMonth() + 1) +'-'+ TimeNow.getDate();
                this.getshipdate = [beginDate,endDate]
                this.getpeding()
            }else{
                var TimeNow = new Date();
                var dayyear = TimeNow.getFullYear();
                var daymonth = this.doHandleMonth(TimeNow.getMonth())
                // console.log(this.doHandleMonth(TimeNow.getMonth()))

                if(this.doHandleMonth(TimeNow.getMonth()) == '00'){
                    dayyear = dayyear - 1
                    daymonth = 12
                }
                let beginDate = dayyear +'-'+ daymonth +'-'+ '01';//当月1号

                let lastDay = new Date(TimeNow.getFullYear(), TimeNow.getMonth(), 0);
                let endDate = dayyear +'-'+ daymonth +'-'+ lastDay.getDate();
                this.getshipdate = [beginDate,endDate]
                this.getpeding()
                // console.log(beginDate,endDate)
            }
        },
        hrefClick(day){
            window.open(process.env.VUE_APP_FBB+'/home/bill/customer?day='+day, '_blank');
        },
        clickNewslist(){
            const url = this.$router.resolve({
                // name: 'homenewList',
                name: 'announceList',
                params: { type: 'query' },
            });
            window.open(url.href, '_blank');
        },
        clickItemNews(id){
            // console.log(id)
            this.itemid = id;
            this.operate = {
                show: true,
                id: id,
                title: "公告",
                component: "compDetail",
                page: 1,
                width: '720',
                showFooter: false
            };
        },
        clickAccount(){
            this.operate = {
                show: true,
                title: "店铺授权",
                component: "compSetAccount",
                width: '800',
                showFooter: false
            };
        },
        timehandle(){
            let beginDate  = this.getDay(-14)
            let endDate = this.getDay(0)
            this.getshipdate = [beginDate,endDate]
            return true
        },
        // 封装时间函数
        getDay(day){
            var today = new Date();
            var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
            today.setTime(targetday_milliseconds); //注意，这行是关键代码
            var tYear = today.getFullYear();
            var tMonth = today.getMonth();
            var tDate = today.getDate();
            tMonth = this.doHandleMonth(tMonth + 1);
            tDate = this.doHandleMonth(tDate);
            return tYear+"-"+tMonth+"-"+tDate;
        },
        doHandleMonth(month){
            var m = month;
            if(month.toString().length == 1){
                m = "0" + month;
            }
            return m;
        },
        async update(){
            
            await this.timehandle()
            // 公告列表
            HttpRecentAnnounceList({
                size: 10
            }).then(res => {
                this.noticeList = res.data.list
            }, err => {
                this.$Message.error(err.message)
            })
            // 获取库存分配
            this.getpie(1)

            //获取账户提醒
            HttpAccountStat().then(res=>{
                // console.log(res.data)
                this.myaccount = res.data
            },err=>{
                this.$Message.error(err.message)
            }) 
            // 根据日期请求销售曲线图
            // 根据存储时间进行是否请求
            var ls= new MyStorage();
            ls.set('timestore','');
            console.log(ls.get("timestore"))
            if(ls.get("timestore") == 'active'){
                this.getStorageData()
            }else{
                ls.set('timestore','active',300000);
                this.getpeding()
            }           

        },
        // 数据存储到storage刷新重新拿出来
        getStorageData(){

            let searchData = localStorage.getItem('searchData')
            let searchDataJson = JSON.parse(searchData);
            this.defaultdate = searchDataJson.defaultIndex;
            this.lineId = searchDataJson.lineIds;
            this.getshipdate = [searchDataJson.beginDate,searchDataJson.endDate];


            let titlebox4 = localStorage.getItem('titlebox4')
            this.titlebox4 = JSON.parse(titlebox4);

            let titlebox3 = localStorage.getItem('titlebox3')
            this.titlebox3 = JSON.parse(titlebox3);

            let datearr1 = localStorage.getItem('datearr1')
            let datearr11 = JSON.parse(datearr1);

            let datearr2 = localStorage.getItem('datearr2')
            let datearr22 = JSON.parse(datearr2);
            datearr11.map(item=>{
                this.beforedaylist.push(item.order_date)
                this.beforeQuantity.push(item.totoal_quantity)
                this.beforeAmount.push(item.total_us_amount)
            })
            datearr22.map(item=>{
                this.nowdaylist.push(item.order_date)
                this.nowQuantity.push(item.totoal_quantity)
                this.nowAmount.push(item.total_us_amount)
            })
            this.alltotal = this.nowQuantity.reduce((val1,val2)=>{
                return val1 + val2
            })
            this.allmount = this.nowAmount.reduce((val1,val2)=>{
                return val1 + val2
            })
            this.drawLine()

            // let titlebox12 = localStorage.getItem('titlebox12')
            // this.titlebox12 = JSON.parse(titlebox12);
          
        },
        // 请求数据
        getpeding(){

            // 查询条件存储
            let searchData = {
                beginDate:this.getshipdate[0],
                endDate:this.getshipdate[1],
                lineIds:this.lineId,
                defaultIndex:this.defaultdate
            }
            localStorage.setItem('searchData',JSON.stringify(searchData))

            this.beforedaylist = [];
            this.beforeQuantity = [];
            this.beforeAmount = [];
            this.nowdaylist = [];
            this.nowQuantity = [];
            this.nowAmount = [];
            this.loading1 = true;
            // 未发货订单
            HttpGetPending({
                beginDate:this.getshipdate[0],
                endDate:this.getshipdate[1],
                lineIds:this.lineId
            }).then(res=>{
                this.titlebox4 = res.data
                localStorage.setItem('titlebox4',JSON.stringify(res.data))
            },err=>{
                // this.$Message.error(err.message)
            })
            // 总退货量
            HttpGetReturn({
                beginDate:this.getshipdate[0],
                endDate:this.getshipdate[1],
                lineIds:this.lineId
            }).then(res=>{
                this.titlebox3 = res.data
                localStorage.setItem('titlebox3',JSON.stringify(res.data))
            },err=>{
                // this.$Message.error(err.message)
            })
            // 请求折线销售数据
            HttpGetSalenData({
                beginDate:this.getshipdate[0],
                endDate:this.getshipdate[1],
                lineIds:this.lineId
            }).then(res=>{
                let arr1 = res.data.before
                let arr2 = res.data.current
                let datearr1 = this.compareFN(arr1,'order_date')
                let datearr2 = this.compareFN(arr2,'order_date')    
                datearr1.map(item=>{
                    this.beforedaylist.push(item.order_date)
                    this.beforeQuantity.push(item.totoal_quantity)
                    this.beforeAmount.push(item.total_us_amount)
                })
                datearr2.map(item=>{
                    this.nowdaylist.push(item.order_date)
                    this.nowQuantity.push(item.totoal_quantity)
                    this.nowAmount.push(item.total_us_amount)
                })
                this.alltotal = this.nowQuantity.reduce((val1,val2)=>{
                    return val1 + val2
                })
                this.allmount = this.nowAmount.reduce((val1,val2)=>{
                    return val1 + val2
                })
                localStorage.setItem('datearr1',JSON.stringify(datearr1))
                localStorage.setItem('datearr2',JSON.stringify(datearr2))
                // console.log(this.compareFN(arr1,'order_date'))
                // console.log(this.compareFN(arr2,'order_date'))
                // 画曲线
                this.drawLine()
                this.loading1 = false
                // console.log(23455)
            },err=>{
                // this.$Message.error(err.message)
            })
        },
        clickpie(type){
            this.showpie = !this.showpie
            this.getpie(type)
        },
        getpie(type){
            this.loading2 = true;
            HttpInventoryProportion({
                countType:type,
            }).then(res=>{
                this.pieList = this.convertKey(res.data, ['name','value'])
                this.loading2 = false
                this.drawPie()
            },err=>{
                // this.$Message.error(err.message)
            })

        },
        compareFN(arr,property) {//比较日期大小函数
            // console.log(arr)
            var i = 0;
            var j = 0;
            let t;
            for ( i = 0; i < arr.length; i++){
                for (j = 0; j < arr.length; j++){
                    let oDate1 = new Date(arr[i][property]);
                    let oDate2 = new Date(arr[j][property]);
                    if (oDate1.getTime() < oDate2.getTime()){
                        t = arr[i];
                        arr[i] = arr[j];
                        arr[j] = t;
                    }
                }
            }
            return arr
        },
        // 转换新数组的方法
        convertKey (arr, key) {
            let newArr = [];
            arr.forEach((item, index) => {
                let newObj = {};
                for (var i = 0; i < key.length; i++) {
                newObj[key[i]] = item[Object.keys(item)[i]]    }
                newArr.push(newObj);
            })  
            // console.log(newArr)  
            return newArr;
        },
        clickliang(){
            this.showliang = !this.showliang;
            this.drawLine()
        },
        scrollList(){
            let that = this;
            const timer = setInterval(() => {
            this.animate = true;
        
            setTimeout(() => {
                that.noticeList.push(this.noticeList[0]);
                that.noticeList.shift();
                that.animate = false;
                // console.log(Math.random());
                }, 500);
            }, 3000);
            // 通过$once来监听定时器，在beforeDestroy钩子可以被清除。
            this.$once("hook:beforeDestroy", () => {
            clearInterval(timer);
            });
        },
        
        drawLine(){
            let lineGraph = Echarts.init(document.getElementById('LineGraph'));
            var colors = ['#5793f3', '#d14a61', '#675bba'];
            let linetitle = this.showliang == false ? ' 订单销售统计 ' : ' 销售额统计 '

            // 拿日期
            let date1 = '去年'
            let date2 = '今年'

            let arrdate=[];
            this.nowdaylist.map(item=>{
                let arritem = item.split('-');
                let jsonone = arritem[1]+ '-' + arritem[2]
                arrdate.push(jsonone)
            })
            // console.log(arrdate)
            // 绘制图表
            lineGraph.setOption({
                title: {
                    text: this.showliang == false ? '订单销售统计' : '销售额统计',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                },
                legend: {
                    left: 'center',
                    data: [date1+linetitle, date2+linetitle],
                    bottom:0
                },
                xAxis: 
                {
                    data: arrdate
                },
                yAxis: {
                    type: 'value',
                },
                grid: {
                    top: '12%',
                    left: '3%',
                    right: '3%',
                    containLabel: true
                },
                series: [
                    {
                        name:date1+linetitle,
                        type:'line',
                        // xAxisIndex: 1,
                        // smooth: true,
                        // stack: linetitle,
                        data: this.showliang == false ? this.beforeQuantity : this.beforeAmount
                    },
                    {
                        name:date2+linetitle,
                        type:'line',
                        // smooth: true,
                        // stack: linetitle,
                        data: this.showliang == false ? this.nowQuantity : this.nowAmount 
                    }
                ]
            })
            window.addEventListener("resize", () => {
                if(lineGraph){
                    lineGraph.resize()
                }
            })
        },
        drawPie(){
            // 自定义颜色
            let colorList = ['#ed4014','#2d8cf0','#19be6b','#d01ec2','#ff9900','#2db7f5','#808695'];
            let pieGraph = Echarts.init(document.getElementById('pieGraph'));
            let titles = this.pieList.map(item=>{
                return item.name
            })
            // console.log(pieGraph)
            pieGraph.setOption({
                title : {
                    text: this.showpie == false ? '库存分布情况' : '体积统计',
                    x:'center'
                },
                tooltip : {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: titles
                },
                color:['#2db7f5','#f90','#808695','#19be6b','#ed3f14'],
                series : [
                    {
                        name: this.showpie == false ? '库存分布情况' : '体积统计',
                        type: 'pie',
                        radius : '55%',
                        center: ['50%', '60%'],
                        data: this.pieList,
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)',
                            }
                        }
                    }
                ]
            })
            window.addEventListener("resize", () => {
                if(pieGraph){
                    pieGraph.resize()
                }
            })
        },
       
    }
}
</script>